<template>
    <div class="crm-talenter-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:talenter:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.talenterName" placeholder="请输入人才姓名" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.mobile" placeholder="请输入手机号码" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <Dictionary v-model="search.qualification" dict-label="crm_qualification_type" placeholder="请选择人才资质"></Dictionary>
                </el-form-item>
                <el-form-item>
                    <Dictionary v-model="search.license" dict-label="crm_license_type" placeholder="请选择人才许可证"></Dictionary>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.remark" placeholder="请输入备注信息" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.userName" placeholder="请输入所属用户名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.deptName" placeholder="请输入所属部门名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.rentalStatus" placeholder="请选择租借状态" clearable class="w100">
                        <el-option label="未租借" value="0"></el-option>
                        <el-option label="已租借" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.expiryStatus" placeholder="请选择到期状态" multiple clearable class="w100">
                        <el-option label="未到期" value="0"></el-option>
                        <el-option label="即将到期" value="1"></el-option>
                        <el-option label="已到期" value="2"></el-option>
                        <el-option label="已续期" value="3"></el-option>
                        <el-option label="已结束" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.examineStatus" placeholder="请选择审核状态" multiple clearable class="w100">
                        <el-option label="草稿" value="0"></el-option>
                        <el-option label="审核中" value="1"></el-option>
                        <el-option label="通过" value="2"></el-option>
                        <el-option label="驳回" value="3"></el-option>
                        <el-option label="撤回" value="4"></el-option>
                        <el-option label="作废" value="5"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.timefield" placeholder="请选择时间" @change="onSearchTimefieldChange" class="w100">
                        <el-option label="创建时间" value="createTime"></el-option>
                        <el-option label="签约时间" value="signStartTime"></el-option>
                        <el-option label="到期时间" value="signEndTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.isAsc" placeholder="请选择排序方式" clearable class="w100">
                        <el-option label="正序" value="asc"></el-option>
                        <el-option label="倒序" value="desc"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more" label="到期天数范围">
                    <el-input-number v-model="search.expiryMinDay" placeholder="Min天数"></el-input-number>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input-number v-model="search.expiryMaxDay" placeholder="Max天数"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:talenter:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmTalenter()">新增</el-button>
            <!-- <el-button v-auth="'crm:talenter:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmTalenter()" :disabled="tableData.selections.length != 1">修改</el-button> -->
            <!-- <el-button v-auth="'crm:talenter:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button> -->
            <el-button v-auth="'crm:rental:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmRental()" :disabled="tableData.selections.length <= 0">租借</el-button>
            <el-table ref="tableCrmTalenterRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column label="人才姓名" prop="talenterName" width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="手机号码" prop="mobile" width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="签约时间" prop="signStartTime" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="到期时间" prop="signEndTime" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="身份证号码" prop="idNumber" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="学历资质" prop="qualification" width="120" show-overflow-tooltip :formatter="loadTalenterQualification"></el-table-column>
                <el-table-column label="许可证书" prop="license" width="120" show-overflow-tooltip :formatter="loadTalenterLicense"></el-table-column>
                <!-- <el-table-column label="电话号码" prop="telephone" width="180" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column label="邮箱号码" prop="email" width="180" show-overflow-tooltip></el-table-column> -->
                <el-table-column label="备注" prop="remark" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="租借状态" prop="rentalStatus" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.rentalStatus == '1'" class="color-success">已租借</span>
                        <span v-else class="color-primary">未租借</span>
                    </template>
                </el-table-column>
                <el-table-column label="到期状态" prop="expiryStatus" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.expiryStatus == '0'" class="color-primary">未到期</span>
                        <span v-else-if="scope.row.expiryStatus == '1'" class="color-warning">即将到期</span>
                        <span v-else-if="scope.row.expiryStatus == '2'" class="color-danger">已到期</span>
                        <span v-else-if="scope.row.expiryStatus == '3'" class="color-success">已续期</span>
                        <span v-else-if="scope.row.expiryStatus == '4'" class="color-info">已结束</span>
                    </template>
                </el-table-column>
                <el-table-column label="到期天数" prop="expiryDay" width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.expiryDay == -99999"></span>
                        <span v-else-if="scope.row.expiryDay >= 0">还有 {{ scope.row.expiryDay }} 天到期</span>
                        <span v-else-if="scope.row.expiryDay < 0" class="color-danger">已到期 {{ -scope.row.expiryDay }} 天，请及时续期</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" prop="examineStatus" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                        <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                        <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                        <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                        <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                        <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                    </template>
                </el-table-column>
                <el-table-column label="所属用户" prop="userName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属部门" prop="deptName" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="130" v-auths="['crm:talenter:info', 'crm:talenter:edit', 'crm:talenter:remove', 'crm:talenter:commited', 'crm:talenter:approved', 'crm:talenter:rejected', 'crm:talenter:canceled', 'crm:talenter:discard', 'crm:talenter:change']">
                    <template #default="scope">
                        <el-button v-auth="'crm:talenter:info'" type="primary" link @click="onOpenInfoCrmTalenter(scope.row)">详情</el-button>
                        <el-dropdown class="ml10" style="vertical-align:unset" v-auths="['crm:talenter:edit', 'crm:talenter:remove', 'crm:talenter:commited', 'crm:talenter:approved', 'crm:talenter:rejected', 'crm:talenter:canceled', 'crm:talenter:discard', 'crm:talenter:change']">
                            <span class="el-dropdown-link">
                                <el-button type="primary" link>更多 <i class="fa fa-angle-down"></i></el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <div v-auth="'crm:talenter:edit'" v-show="['0','2','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmTalenter(scope.row, 'edit')">修改</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:remove'" v-show="['0','3','4','5'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:commited'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '1')">提交</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:approved'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '2')">通过</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:rejected'" v-show="['1','2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '3')">驳回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:canceled'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '4')">撤回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:discard'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '5')">作废</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:renewal'" v-show="!['3'].includes(scope.row.expiryStatus) && ['2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmTalenter(scope.row, 'renewal')">续期</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:finished'" v-show="!['4'].includes(scope.row.expiryStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenFinishedCrmTalenter(scope.row)">终止</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:talenter:change'">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenChangeCrmTalenter(scope.row)">变更</el-button>
                                        </el-dropdown-item>
                                    </div>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmTalenter ref="addCrmTalenterRef" @submit="onTableSearch"/>
        <EditCrmTalenter ref="editCrmTalenterRef" @submit="onTableSearch"/>
        <ChangeCrmTalenter ref="changeCrmTalenterRef" @submit="onTableSearch"/>
        <InfoCrmTalenter ref="infoCrmTalenterRef"></InfoCrmTalenter>
        <AddCrmRental ref="addCrmRentalRef" @submit="onTableSearch"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddCrmTalenter from '/@/views/crm/talenter/addCrmTalenter.vue';
import EditCrmTalenter from '/@/views/crm/talenter/editCrmTalenter.vue';
import ChangeCrmTalenter from '/@/views/crm/talenter/changeCrmTalenter.vue';
import InfoCrmTalenter from '/@/views/crm/talenter/infoCrmTalenter.vue';
import AddCrmRental from '/@/views/crm/rental/addCrmRental.vue';
import Dictionary from '/@/components/dictionary/index.vue';
import { getCrmTalenterList, delCrmTalenter, examineCrmTalenter, finishedCrmTalenter } from '/@/api/crm/talenter/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
import { getDictionaryByLabel } from '/@/api/system/dictionary/index';
export default {
    name: 'crm/talenter',
    components: { AddCrmTalenter, EditCrmTalenter, ChangeCrmTalenter, InfoCrmTalenter, AddCrmRental, Dictionary },
    setup() {
        const tableCrmTalenterRef = ref();
        const addCrmTalenterRef = ref();
        const editCrmTalenterRef = ref();
        const changeCrmTalenterRef = ref();
        const infoCrmTalenterRef = ref();
        const addCrmRentalRef = ref();
        const state = reactive({
            qualifications: [],
            licenses: [],
            search:{
                talenterName: undefined,
                qualification: undefined,
                license: undefined,
                mobile: undefined,
                remark: undefined,
                userName: undefined,
                deptName: undefined,
                rentalStatus: undefined,
                expiryStatus: [],
                examineStatus: [],
                expiryMinDay: undefined,
                expiryMaxDay: undefined,
                timefield: 'createTime',
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData = (params) => {
            const search = { ...state.search, ...params };
            const expiryStatusStr = search.expiryStatus.join(',');
            const examineStatusStr = search.examineStatus.join(',');
            getCrmTalenterList({
                ...search,
                expiryStatus: expiryStatusStr,
                examineStatus: examineStatusStr
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmTalenterRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.talenterName = undefined;
            state.search.qualification = undefined;
            state.search.license = undefined;
            state.search.mobile = undefined;
            state.search.remark = undefined;
            state.search.userName = undefined;
            state.search.deptName = undefined;
            state.search.rentalStatus = undefined;
            state.search.expiryStatus = [];
            state.search.examineStatus = [];
            state.search.expiryMinDay = undefined;
            state.search.expiryMaxDay = undefined;
            state.search.timefield = 'createTime';
            state.search.orderBy = 'createTime';
            state.search.isAsc = 'desc';
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        const onSearchTimefieldChange = (value: string) => {
            state.search.orderBy = value;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmTalenter = (row?: object) => {
            addCrmTalenterRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmTalenter = (row: object, operate: string) => {
            row = row || state.tableData.selections[0];
            row.operate = operate;
            editCrmTalenterRef.value.openDialog(row);
        };
        // 打开变更弹窗
        const onOpenChangeCrmTalenter = (row: object) => {
            row = row || state.tableData.selections[0];
            changeCrmTalenterRef.value.openDialog(row);
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的人才信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmTalenter(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条人才信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmTalenter([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        const onOpenInfoCrmTalenter = (row: object) => {
            infoCrmTalenterRef.value.openDialog(row);
        };

        const loadTalenterQualification = (row, column, cellValue, index) => {
            return state.qualifications.find((item) => item.dictValue == cellValue)?.dictName;
        }
        const loadTalenterLicense = (row, column, cellValue, index) => {
            return state.licenses.find((item) => item.dictValue == cellValue)?.dictName;
        }
        const examineStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '提交',
                '2': '通过',
                '3': '驳回',
                '4': '撤回',
                '5': '作废'
            };
            return statusMap[status] || '未知';
        };
        
        const onOpenExamineRecordStatus = (row: object, status: String) => {
            if(['1', '2', '4', '5'].includes(status)){
                ElMessageBox.confirm(`确认【${ examineStatusText(status) }】操作吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    examineCrmTalenter({ examineTargetId: row.id, status: status }).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('操作成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }else{
                ElMessageBox.prompt('请输入驳回原因：', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then((message) => {
                    if (!message.value || message.value.trim() === '') {
                        ElMessage.error('驳回原因不能为空，请重新输入！');
                    } else {
                        examineCrmTalenter({ examineTargetId: row.id, status: status, examineReason: message.value }).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('操作成功');
                                loadTableData({});
                            }
                        });
                    }
                }).catch(() => {});
            }
        };
        const onOpenFinishedCrmTalenter = (row: object) => {
            ElMessageBox.confirm(`确认【终止】合作操作吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                finishedCrmTalenter([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('操作成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };
        // 打开新增弹窗
        const onOpenAddCrmRental = (row?: object) => {
            if(state.tableData.selections.filter(item => item.examineStatus != 2).length > 0){
                ElMessage.error('审核未通过的人才不能租借');
                return;
            }
            if(state.tableData.selections.filter(item => item.rentalStatus == 1).length > 0){
                ElMessage.error('已租借的人才不能再次租借');
                return;
            }
            const talenterIds = state.tableData.selections.map(item => item.id);
            addCrmRentalRef.value.openDialog({
                talenterIds: talenterIds,
                talenters: state.tableData.selections,
            });
        };
        // 页面加载时
        onMounted(() => {
            loadTableData({});
            getDictionaryByLabel({ dictLabel: 'crm_qualification_type' }).then((res: any) => {
                if (res.code == 0) {
                    state.qualifications = res.data;
                }
            });
            getDictionaryByLabel({ dictLabel: 'crm_license_type' }).then((res: any) => {
                if (res.code == 0) {
                    state.licenses = res.data;
                }
            });
        });
        return {
            tableCrmTalenterRef,
            addCrmTalenterRef,
            editCrmTalenterRef,
            changeCrmTalenterRef,
            infoCrmTalenterRef,
            addCrmRentalRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onSearchTimefieldChange,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmTalenter,
            onOpenEditCrmTalenter,
            onOpenInfoCrmTalenter,
            onTabelRowsDel,
            onTabelRowDel,
            loadTalenterQualification,
            loadTalenterLicense,
            examineStatusText,
            onOpenExamineRecordStatus,
            onOpenChangeCrmTalenter,
            onOpenFinishedCrmTalenter,
            onOpenAddCrmRental,
            ...toRefs(state),
        };
    },
};
</script>